//
//  AppDelegate.m
//  Doctor
//
//  Created by 阳光 on 16/9/5.
//  Copyright © 2016年 阳光. All rights reserved.
//

#import "AppDelegate.h"
#import "QBMainVC.h"
#import "NewFeatureVC.h"
#import "LoginVC.h"

#import "ConfirmVC.h"

#import "NIMSDK.h"
#import "UIView+Toast.h"
#import "NTESService.h"
#import "NTESNotificationCenter.h"
#import "NTESLogManager.h"
#import "NTESDemoConfig.h"
#import "NTESSessionUtil.h"
#import "NTESLoginManager.h"
#import "NTESCustomAttachmentDecoder.h"
#import "NTESClientUtil.h"
#import "NTESNotificationCenter.h"
#import "NIMKit.h"
#import "NTESDataManager.h"
#import "NTESSDKConfig.h"
NSString *NTESNotificationLogout = @"NTESNotificationLogout";

@interface AppDelegate ()<NIMLoginManagerDelegate>
@property (nonatomic,strong) NTESSDKConfig *config;
@end



@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor=WhiteColor;
    [_window makeKeyAndVisible];
    
    //IM配置
    [self configureIMSDKAction];//.
    
    [self isFirstOpenApp];
    
    //版本更新
    [self updateAppVersion];
    
    [self GETl];

    
    return YES;
}


-(void)GETl
{
    [QBRequest GetCountryInfoWithDic:nil Success:^(id res)
     {
         NSLog(@"209923093282--%@",res);
         
         //         weakSelf.countryListArr=[CountryListModel mj_objectArrayWithKeyValuesArray:res[@"info"]];
         //
         //         [weakSelf.countryListTableView reloadData];
         //
         //         [weakSelf.countryListTableView.mj_header endRefreshing];
         
     } failure:^(NSString *error)
     {
         //         [self.view makeToast:error duration:1.0 position:CSToastPositionCenter];
         //         [weakSelf.countryListTableView.mj_header endRefreshing];
     }];
    
}

// 判断是否第一次启动app
-(void)isFirstOpenApp{
    
    // 此为找到plist文件中得版本号所对应的键
    NSString *key = @"CFBundleShortVersionString";
    // 1.从plist中取出版本号
    NSString *version=[NSBundle mainBundle].infoDictionary[key];
    // 2.从沙盒中取出上次存储的版本号
    NSString *saveVersion=[[NSUserDefaults standardUserDefaults]objectForKey:key];
    
    NSString *hasConfirmDoneStr=[Util getUserDefaultObjectForKey:HasConfirmDone];
    if ((saveVersion &&[version isEqualToString:saveVersion]) && ([hasConfirmDoneStr isEqualToString:@"YES"])){
        
        // 不是第一次使用这个版本  进入主界面
        [self startApp];
    
    }else{
        
        // 版本号不一样：为第一次使用新版本
        NewFeatureVC *newFeatureVC=[NewFeatureVC new];
        NSMutableArray *arr=[NSMutableArray new];
        // 判断所使用的语言
        BOOL isCN = [[LanguageConvert alloc] hasShownIsCnOrNot];
        // 中文
        if (isCN == YES)
        {
            [arr addObject:[NSString stringWithFormat:@"qb_launch_cn"]];
        }
        // 英文
        else if (isCN == NO)
        {
            [arr addObject:[NSString stringWithFormat:@"qb_launch_en"]];
        }
        
        newFeatureVC.images=arr;
        [newFeatureVC setStart:^{
            
            // 将新版本号写入沙盒
            [[NSUserDefaults standardUserDefaults]setObject:version forKey:key];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            // 进入主界面
            [self startApp];
            
        }];
        self.window.rootViewController=newFeatureVC;
    }
    
    self.window.backgroundColor=WhiteColor;
    [self.window makeKeyAndVisible];
}

-(void)startApp{

    NSString *hasLoginStr=[Util getUserDefaultObjectForKey:HasConfirmDone];

    if ([hasLoginStr isEqualToString:@"YES"]){
        
        [self setupMainViewController];
        
    }else{
        
        [self goLoginVC];
    }
    
}

-(void)goHomePageVC{
    
    QBMainVC *mainVC=[[QBMainVC alloc] init];
    self.window.rootViewController=mainVC;
    [_window makeKeyAndVisible];
    _window.backgroundColor=WhiteColor;
    
}

-(void)goLoginVC{
    
    LoginVC *loginVC=[LoginVC new];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = navi;
}


//提示框
- (void)showMessageByMessage:(NSString *)message{
    
    [AlertLabel hudShowText:message];
}



#pragma mark - 版本更新
-(void)updateAppVersion{
    
    
    [QBRequest IsNewVersionWithSuccess:^(id res){
        
       // NSLog(@"res :%@", res);
        NSDictionary *info = res[@"info"];
        NSString *isHasUpdate = info[@"is"];
        NSString *isForceUpdate = info[@"qz"];
        
        if ([isHasUpdate isEqual:@0]) {
            
            //目前为最新版本;
            
        } else if ([isHasUpdate isEqual:@1]){
            
            if ([isForceUpdate isEqual:@0]) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Has new version", nil) message:NSLocalizedString(@"Update or not", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Sure", nil) otherButtonTitles:NSLocalizedString(@"Cancel", nil), nil];
                alert.tag = 100;
                alert.delegate = self;
                [alert show];
                
            } else if ([isForceUpdate isEqual:@1]){
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Find new version", nil) message:NSLocalizedString(@"Update now", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Sure", nil) otherButtonTitles:nil, nil];
                alert.tag = 110;
                alert.delegate = self;
                [alert show];
            }
        }
        
    } failure:^(NSString *error){
        
    }];
}


//版本更新
- (void)versionUpdateAction{
    
    NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/en/app/id1063640465"];//1063640465
    
    [[UIApplication sharedApplication] openURL:url];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ((alertView.tag == 100) || (alertView.tag == 110)) {
        
        if (buttonIndex == 0) {
            
            [self versionUpdateAction];
        }
    }
    
}



#pragma mark - IMConfigure
//IM配置:
- (void)configureIMSDKAction{
    
    _config = [[NTESSDKConfig alloc] init];
    
    [[NIMSDKConfig sharedConfig] setDelegate:_config];
    
    NSString *appKey = [[NTESDemoConfig sharedConfig] appKey];
    NSString *cerName= [[NTESDemoConfig sharedConfig] cerName];
    [[NIMSDK sharedSDK] registerWithAppID:appKey cerName:cerName];//初始化
    
    [NIMCustomObject registerCustomDecoder:[NTESCustomAttachmentDecoder new]];
    
    [self setupServices];
    
    [self registerAPNs];
    
    [self commonInitListenEvents];
    
    [[NIMKit sharedKit] setProvider:[NTESDataManager sharedInstance]];
    
    //    [self setupMainViewController];
    //    [[NIMSDK sharedSDK] enableConsoleLog];//log;
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[[NIMSDK sharedSDK] loginManager] removeDelegate:self];
}


#pragma mark - misc
- (void)setupServices{
    
    [[NTESLogManager sharedManager] start];
    [[NTESNotificationCenter sharedCenter] start];
}


-(void)registerAPNs{
    
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)])
    {
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        UIRemoteNotificationType types = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    }
}


- (void)commonInitListenEvents{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(logout:)
                                                 name:NTESNotificationLogout
                                               object:nil];
    
    [[[NIMSDK sharedSDK] loginManager] addDelegate:self];
}

- (void)setupMainViewController{
    
    LoginData *data = [[NTESLoginManager sharedManager] currentLoginData];
    NSString *account = [data account];
    NSString *token = [data token];
    
    //如果有缓存用户名密码推荐使用自动登录
    if ([account length] && [token length]){
        
        [[[NIMSDK sharedSDK] loginManager] autoLogin:account
                                               token:token];
        [[NTESServiceManager sharedManager] start];
        
        //主页
        [self  goHomePageVC];
        
    }else{
        
        //登录
        [self setupLoginViewController];
    }
}

- (void)setupLoginViewController{
    
    [self goLoginVC];
}




//- 注销
-(void)logout:(NSNotification *)note{
    
    [self doLogout];
}

- (void)doLogout{
    
    [[NTESLoginManager sharedManager] setCurrentLoginData:nil];
    [[NTESServiceManager sharedManager] destory];
    
    [self setupLoginViewController];
}




#pragma mark - ApplicationDelegate
- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    NSInteger count = [[[NIMSDK sharedSDK] conversationManager] allUnreadCount];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken];
//    DDLogInfo(@"didRegisterForRemoteNotificationsWithDeviceToken:  %@", deviceToken);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
//    DDLogInfo(@"receive remote notification:  %@", userInfo);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{

//    DDLogError(@"fail to get apns token :%@",error);
}



#pragma mark - NIMLoginManagerDelegate
-(void)onKick:(NIMKickReason)code clientType:(NIMLoginClientType)clientType{
    
    NSString *reason = @"你被踢下线";
    switch (code) {
        case NIMKickReasonByClient:
        case NIMKickReasonByClientManually:{
            NSString *clientName = [NTESClientUtil clientName:clientType];
            reason = clientName.length ? [NSString stringWithFormat:@"你的帐号被%@端踢出下线，请注意帐号信息安全",clientName] : @"你的帐号被踢出下线，请注意帐号信息安全";
            break;
        }
        case NIMKickReasonByServer:
            reason = @"你被服务器踢下线";
            break;
        default:
            break;
    }
    [[[NIMSDK sharedSDK] loginManager] logout:^(NSError *error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:NTESNotificationLogout object:nil];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"下线通知" message:reason delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];//.
    }];
}

- (void)onAutoLoginFailed:(NSError *)error{
    
    //只有连接发生严重错误才会走这个回调，在这个回调里应该登出，返回界面等待用户手动重新登录。
//    DDLogInfo(@"onAutoLoginFailed %zd",error.code);
    [self.window makeToast:[NSString stringWithFormat:@"登录失败: %zd",error.code] duration:2.0 position:CSToastPositionCenter];
    [[[NIMSDK sharedSDK] loginManager] logout:^(NSError *error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:NTESNotificationLogout object:nil];
    }];
    
}





// 清除用户信息
-(void)clearUserData{
    
    [UserDefaults userDefaultsRemove:@"access_token_token"];
    [UserDefaults userDefaultsRemove:@"id"];
    [UserDefaults userDefaultsRemove:@"username"];
    [UserDefaults userDefaultsRemove:@"key"];
    [UserDefaults userDefaultsRemove:@"yuxin"];
    [UserDefaults userDefaultsRemove:@"accid"];
    [UserDefaults userDefaultsRemove:@"token"];
    [UserDefaults userDefaultsRemove:@"info"];
    [UserDefaults userDefaultsRemove:@"auth_status"];
    [Util saveObjectToUserDefault:@"NO" forKey:HasLoginClick];
    [Util saveObjectToUserDefault:@"NO" forKey:HasConfirmDone];
    
    [self UserLogOut];
    
}

//登出
-(void)UserLogOut{
    
    [[[NIMSDK sharedSDK] loginManager] logout:^(NSError *error){
         [[NSNotificationCenter defaultCenter] postNotificationName:NTESNotificationLogout object:nil];
     }];

}




@end

